package cn.scp.qrCode.service.impl;

import cn.scp.qrCode.service.TestService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Notice:
 *
 * @author scp
 * @version 1.0
 * @date 2021/4/19
 * @since 1.0
 */
@Service
public class TestServiceImpl implements TestService {

    @Override
    public void test() throws WriterException, IOException {
        //需要编码的内容
        String urlCode = "meizi 毕设";
        QRCodeWriter qrCodeWriter1 = new QRCodeWriter();
        // 设置编码
        Map<EncodeHintType,String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置二维码图片宽高
        BitMatrix bitMatrix1 = qrCodeWriter1.encode(urlCode, BarcodeFormat.QR_CODE, 600, 600, hints);
        //输出到指定路径
        Path path = FileSystems.getDefault().getPath("D:/files/MyQRCode.png");
        MatrixToImageWriter.writeToPath(bitMatrix1, "PNG", path);
        // 写到输出流
        ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix1, "PNG", outputStream1);
        //转换为base64
        Base64.Encoder encoder1 = Base64.getEncoder();
        String advUrl = "data:image/jpeg;base64,"
                + encoder1.encodeToString(outputStream1.toByteArray());
        //打印base64结果
        System.out.println(advUrl);
    }
}
